package cc.javaee.bbs.tool;

import java.util.*;

/**
 * @author xdw
 */
public class StringUtil {

    private static class Constants {
        //序列字符池
        public static final String ORDER_CHAR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //十六进制数字
        public static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        //种子
        public static final int seed = 2009;
    }

    public static String getShortUUID() {
        //获取uuid
        String[] aStr = UUID.randomUUID().toString().split("-");

        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < aStr.length; i++) {
            //固定种子,确保取值池是相同的,以确保最后取值绝对不会重复
            sb.append(baseString(Long.parseLong(aStr[i], 16), disorganize(new Random(Constants.seed))));
        }
        return sb.toString();
    }

    public static String baseString(long num, String scope) {
        int base = scope.length();
        String str = "";
        if (num == 0) {
            return "";
        } else {
            str = baseString(num / base, scope);
            return str + scope.charAt((int) (num % base));
        }
    }


    /**
     * 指定规则打乱
     *
     * @param str
     * @return
     */
    public static String disorganize(String str, Random rd) {
        if (str == null || "".equals(str)) {
            str = Constants.ORDER_CHAR;
        }
        if (rd == null) {
            rd = new Random();
        }
        List<String> list = Arrays.asList(str.split(""));
        Collections.shuffle(list, rd);
        StringBuffer sb = new StringBuffer();
        for (String s : list) {
            sb.append(s);
        }
        return sb.toString();
    }

    public static String disorganize(String str) {
        return disorganize(str, null);
    }

    public static String disorganize(Random rd) {
        return disorganize(null, rd);
    }

}
